<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>管理系统</title>
    <link rel="stylesheet" href="../plugins/element-ui/index.css">
    <script src="../plugins/vue/vue.js"></script>
    <script src="../plugins/element-ui/index.js"></script>
    <script src="../plugins/axios/axios.min.js"></script>
    <script src="../plugins/request.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            margin: 20px;
        }

        .sidebar {
            width: 250px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .content {
            flex: 1;
            padding: 20px;
            background-color: #fff;
            margin-left: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .category-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #fafafa;
        }

        .category-info {
            display: flex;
            align-items: center;
        }

        .order-info {
            display: flex;
            align-items: center;
        }

        .order-item {
            flex: 1 1 200px;
            margin: 10px;
        }

        .order-items {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        .category-info img {
            margin-right: 10px;
            border-radius: 5px;
        }

        .purchase-section {
            display: flex;
            align-items: center;
        }

        .purchase-section button {
            margin: 0 5px;
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            background-color: #409EFF;
            color: #fff;
            cursor: pointer;
        }

        .purchase-section button:hover {
            background-color: #66b1ff;
        }

        .purchase-section span {
            margin: 0 10px;
            font-size: 16px;
        }

        .global-button {
            position: fixed;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }

        .global-button img {
            margin-right: 5px;
        }

        .user-item {
            background-color: #f9f9f9;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }

        .beijing {
            background-color: #c6e2ff;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }

        .erji {
            background-color: #c6e2ff;
        }

        .order-image {
            width: 100px;
            margin-right: 20px;
        }

        .order-details {
            display: flex;
            flex-direction: column;
            flex: 1;
        }

        .order-group h4 {
            margin-bottom: 10px;
            color: #333;
        }

        .order-group {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
            background-color: #e0f7fa;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
<h1 style="text-align: center; margin-top: 20px;">管理系统</h1>

<div id="app" class="container">
    <div class="sidebar">
        <el-menu :default-active="activeMenu" class="el-menu-vertical-demo" @select="handleSelect">
            <el-menu-item index="1" class="beijing">新闻公告</el-menu-item>
            <el-submenu index="2" class="beijing">
                <template slot="title">商品</template>
                <el-menu-item index="2-0" class="erji">全部</el-menu-item>
                <el-menu-item index="2-1" class="erji">电子产品</el-menu-item>
                <el-menu-item index="2-2" class="erji">零食</el-menu-item>
                <el-menu-item index="2-3" class="erji">日常用品</el-menu-item>
            </el-submenu>
            <el-menu-item index="3" class="beijing">用户信息</el-menu-item>
            <el-menu-item index="4" class="beijing">用户订单</el-menu-item>
        </el-menu>
    </div>
    <div class="content">
        <h2 v-if="activeMenu === '3'">信息</h2>
        <h2 v-if="activeMenu === '4'">订单</h2>

        <div v-if="activeMenu === '3' && userList.length > 0">
            <h3>用户列表</h3>
            <div v-for="user in userList" :key="user.id" class="user-item">
                <h3 @click="showUserDetails(user)">{{ user.username }}</h3>
            </div>
        </div>
        <el-dialog :visible.sync="showUserDetailsModal" title="用户详情">
            用户名
            <el-input v-model="userInfo.username" placeholder="用户名"></el-input>
            密码
            <el-input v-model="userInfo.password" placeholder="密码"></el-input>
            电话
            <el-input v-model="userInfo.phone" placeholder="电话"></el-input>
            地址
            <el-input v-model="userInfo.email" placeholder="地址"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showUserDetailsModal = false">关闭</el-button>
                <el-button type="primary" @click="updateUserInfo">修改</el-button>
                <el-button type="danger" @click="deleteUser(userInfo.id)">删除</el-button>
            </span>
        </el-dialog>


        <el-dialog :visible.sync="showAddProductModal" title="添加商品">
            <el-form :model="newcategories">
                <el-form-item label="商品名称">
                    <el-input v-model="newcategories.name"></el-input>
                </el-form-item>
                <el-form-item label="商品价格">
                    <el-input v-model="newcategories.price"></el-input>
                </el-form-item>
                <el-form-item label="商品种类">
                    <el-select v-model="newcategories.kind" placeholder="请选择">
                        <el-option label="电子产品" value="1"></el-option>
                        <el-option label="零食" value="2"></el-option>
                        <el-option label="日常用品" value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品图片">
                    <el-upload>
                        <!--                        class="avatar-uploader"-->
                        <!--                        action="/admin/upload"-->
                        <!--                        :show-file-list="false"-->
                        <!--                        :on-success="handleSuccess"-->
                        <!--                        :on-error="handleError"-->

                        <!--                        :before-upload="beforeUpload">-->
                        <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>


                    <!--                <el-form-item label="商品图片">-->
                    <!--                    <el-upload-->
                    <!--                            class="avatar-uploader"-->
                    <!--                            action="/admin/upload"-->
                    <!--                            :show-file-list="false"-->
                    <!--                            :on-success="handleSuccess"-->
                    <!--                            :on-error="handleError"-->
                    <!--                            :before-upload="beforeUpload">-->
                    <!--                        &lt;!&ndash;        :headers="{'Content-Type': 'multipart/form-data'}">&ndash;&gt;-->
                    <!--                        <img v-if="newcategories.image" :src="newcategories.image" class="avatar">-->
                    <!--                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                    <!--                    </el-upload>-->
                    <!--                </el-form-item>-->
                    <el-button @click="addProduct" type="primary">添加</el-button>
                    <el-button @click="showAddProductModal = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>


        <div v-if="activeMenu === '4' && orders.length > 0">
            <div v-for="order in orders" :key="order.id" class="order-group">
                <h4>订单号: {{ order.id }}</h4> <h4>用户名: {{ order.username }}</h4>
                <div class="order-items">
                    <div v-for="detail in order.details" :key="detail.id" class="order-item">
                        <div class="order-info">
                            <img :src="detail.image" alt="detail.name" class="order-image">
                            <div class="order-details">
                                <h4>{{ detail.name }}</h4>
                                <p>数量: {{ detail.num }}</p>
                                <p>价格: {{ detail.price }}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <p>总价: {{ order.fprice }}</p>
            </div>
            <el-pagination
                    @current-change="handlePageChange"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="totalOrders">
            </el-pagination>
        </div>

        <div v-if="activeMenu === '1'">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h2>新闻公告</h2>
                <el-button type="primary" @click="showPublishModal = true">发布</el-button>
            </div>
            <div v-if="news && news.length" class="user-item">
                <div v-for="item in news" :key="item.id">
                    <h3 @click="showNewsDetails(item)">{{ item.title }} - {{ item.date }}</h3>
                </div>
            </div>
        </div>

        <el-dialog :visible.sync="showDetailsModal" title="新闻详情">
            <h3>{{ selectedNews.title }}</h3>
            <p>{{ selectedNews.content }}</p>
            <p>{{ selectedNews.date }}</p>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showDetailsModal = false">关闭</el-button>
                <el-button type="danger" @click="deleteNews(selectedNews.id)">删除</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="showPublishModal" title="发布新闻公告">
            <el-input v-model="newNewsTitle" placeholder="新闻标题"></el-input>
            <el-input type="textarea" v-model="newNewsContent" placeholder="新闻内容"></el-input>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showPublishModal = false">取消</el-button>
                <el-button type="primary" @click="publishNews">发布</el-button>
            </span>
        </el-dialog>

        <h2 v-if="activeMenu !== '1' && activeMenu !== '3' && activeMenu !== '4'">商品信息
            <el-button type="primary" @click="showAddProductModal = true">添加商品</el-button>
        </h2>
        <div v-if="activeMenu !== '1' && activeMenu !== '3' && activeMenu !== '4'"
             v-for="category in categories"
             :key="category.id"
             class="category-item">
            <div class="category-info" @click="openCategoryModal(category)">
                <img :src="category.image" alt="category.name" width="100">
                <h3>{{ category.name }}</h3>
            </div>
            <div class="purchase-section">
                <button @click.stop="addToCart(category)">加入购物车</button>
            </div>
        </div>
        <el-dialog :visible.sync="showCategoryModal" title="商品详情">
            <div v-if="selectedCategory">
                <img :src="selectedCategory.image" alt="selectedCategory.name" width="100">
                <p>商品名称：</p>
                <el-input v-model="selectedCategory.name" placeholder="商品名称"></el-input>
              <p>商品价格:</p>
                <el-input v-model="selectedCategory.price" placeholder="商品价格"></el-input>
               <p>商品种类:</p>
                <el-select v-model="selectedCategory.kind" placeholder="商品种类">
                    <el-option label="电子产品" value="1"></el-option>
                    <el-option label="零食" value="2"></el-option>
                    <el-option label="日常用品" value="3"></el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
        <el-button @click="showCategoryModal = false">关闭</el-button>
        <el-button type="primary" @click="updateCartItem(selectedCategory)">修改</el-button>
        <el-button type="danger" @click="deleteCartItem(selectedCategory.shopid)">删除</el-button>
    </span>
        </el-dialog>
    </div>
</div>

<script>

    new Vue({
        el: '#app',
        data() {
            return {
                showAddProductModal: false,
                newcategories: {
                    name: '',
                    price: '',
                    kind: '',
                    image: ''
                },
                orders: [],
                totalOrders: 0,
                currentPage: 1,
                pageSize: 10,
                activeMenu: '1',
                categories: [],
                news: [],
                cartModalVisible: false,
                selectedCategory: null,
                shopingCar: [],
                showCartModal: false,
                cartNotEmpty: false,
                userInfo: {},
                username: '',
                showPublishModal: false,
                newNewsTitle: '',
                newNewsContent: '',
                showDetailsModal: false,
                selectedNews: {},
                userList: [],
                showUserDetailsModal: false,
                showCategoryModal: false,


            };
        },
        mounted() {
            this.fetchNews();
            this.fetchShopingCar();
            this.fetchUserInfo();
            this.fetchUserList();
            this.username = localStorage.getItem('username') || this.getQueryParam('username');
        },

        methods: {
            fetchCategories(categoryId) {
                let url = '/categories/' + categoryId;
                axios.get(url)
                    .then(response => {
                        this.categories = response.data.map(category => {
                            const cartItem = this.shopingCar.find(item => item.id === category.id);
                            return {
                                ...category,
                                num: cartItem ? cartItem.num : category.num,
                                inCart: !!cartItem
                            };
                        });
                        console.log(this.categories);
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            confirmCart() {
                axios.get('/categories/list')
                    .then(response => {
                        console.log('Categories list:', response.data);
                        this.categories = response.data.map(category => {
                            const cartItem = this.shopingCar.find(item => item.id === category.id);
                            return {
                                ...category,
                                num: cartItem ? cartItem.num : category.num,
                                inCart: !!cartItem
                            };
                        });
                        this.showCartModal = false;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            handleSelect(key, keyPath) {
                console.log(key, keyPath);
                this.activeMenu = key;
                if (key === '1') {
                    this.fetchNews();
                } else if (key === '2-0') {
                    this.fetchCategories('list');
                } else if (key === '2-1') {
                    this.fetchCategories('1');
                } else if (key === '2-2') {
                    this.fetchCategories('2');
                } else if (key === '2-3') {
                    this.fetchCategories('3');
                } else if (key === '3') {
                    this.fetchUserInfo();
                } else if (key === '4') {
                    this.fetchOrders();
                }
            },
            fetchUserInfo() {
                axios.get('/admin/select')
                    .then(response => {
                        this.userInfo = response.data;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            updateUserInfo() {
                axios.post('/user/update', this.userInfo)
                    .then(response => {
                        alert('用户信息更新成功');
                        this.showUserDetailsModal = false;
                    })
                    .catch(error => {
                        console.error(error);
                        alert('更新失败');
                    });
            },
            fetchNews() {
                axios.get('/news/getnews')
                    .then(response => {
                        if (response.data === 'NOTLOGIN') {
                            window.location.href = '/front/login.html';
                        } else {
                            this.news = response.data;
                            console.log(this.news);
                        }
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            fetchShopingCar() {
                axios.get('/categories/getShopingCar')
                    .then(response => {
                        console.log('Shoping car:', response.data);
                        this.shopingCar = response.data.map(item => ({
                            ...item,
                            num: item.num
                        }));
                        this.cartNotEmpty = this.shopingCar.length > 0;
                        this.updateCategoriesWithCart();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            openCartModal(category) {
                this.selectedCategory = {...category, num: category.num || 1};
                this.cartModalVisible = true;
            },
            addToCart(category) {
                category.inCart = true;
                category.num = 1;
                this.cartNotEmpty = true;
                this.cartModalVisible = false;

                axios.post('/categories/add', {
                    ...category,
                    num: category.num
                })
                    .then(response => {
                        console.log('Added to cart:', response.data);
                        this.fetchShopingCar();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            increaseQuantity(category) {
                category.num++;
                axios.post('/categories/add', {
                    ...category,
                    num: category.num
                })
                    .then(response => {
                        console.log('Increased quantity:', response.data);
                        this.fetchShopingCar();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            updateCategoriesWithCart() {
                this.categories = this.categories.map(category => {
                    const cartItem = this.shopingCar.find(item => item.id === category.id);
                    return {
                        ...category,
                        num: cartItem ? cartItem.num : category.num,
                        inCart: !!cartItem
                    };
                });
            },
            decreaseQuantity(category) {
                if (category.num > 1) {
                    category.num--;
                    axios.post('/categories/jian', {
                        ...category,
                        num: category.num
                    })
                        .then(response => {
                            console.log('Decreased quantity:', response.data);
                            this.fetchShopingCar();
                        })
                        .catch(error => {
                            console.error(error);
                        });
                } else {
                    category.num = 0;
                    category.inCart = false;
                    axios.post('/categories/jian', {
                        ...category,
                        num: 0
                    })
                        .then(response => {
                            console.log('Removed from cart:', response.data);
                            this.cartNotEmpty = this.shopingCar.length > 0;
                            this.fetchShopingCar();
                        })
                        .catch(error => {
                            console.error(error);
                        });
                }
            },
            redirectToPay() {
                window.location.href = '/front/pay.html';
            },
            redirectToMyInfo() {
                this.activeMenu = '3';
                this.fetchUserInfo();
            },
            getQueryParam(param) {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get(param);
            },
            logout() {
                axios.get('/user/logout')
                    .then(response => {
                        this.$notify({
                            title: 'Success',
                            message: '登出成功',
                            type: 'success'
                        });
                        setTimeout(() => {
                            window.location.href = '/front/login.html';
                        }, 1000);
                    })
                    .catch(error => {
                        this.$notify({
                            type: 'error',
                            title: 'Error',
                            message: '登出失败'
                        });
                        console.error(error);
                    });
            },
            fetchOrders(pageNum = 1, pageSize = 10) {
                axios.get('/admin/get', {
                    params: {
                        pageNum: pageNum,
                        pageSize: pageSize
                    }
                })
                    .then(response => {
                        console.log('Orders:', response.data);
                        this.orders = response.data.records;
                        this.totalOrders = response.data.total;
                        this.currentPage = pageNum;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            handlePageChange(page) {
                this.fetchOrders(page, this.pageSize);
            },
            publishNews() {
                axios.post('/news/publish', {
                    title: this.newNewsTitle,
                    content: this.newNewsContent
                })
                    .then(response => {
                        console.log('News published:', response.data);
                        alert('新闻公告发布成功');
                        this.fetchNews(); // 重新获取新闻公告
                        this.showPublishModal = false; // 关闭弹窗
                        this.newNewsTitle = ''; // 清空表单
                        this.newNewsContent = '';
                    })
                    .catch(error => {
                        console.error(error);
                        alert('发布失败');
                    });
            },
            showNewsDetails(news) {
                this.selectedNews = news;
                this.showDetailsModal = true;
            },
            deleteNews(newsId) {
                axios.delete(`/news/delete/${newsId}`)
                    .then(response => {
                        console.log('News deleted:', response.data);
                        alert('新闻公告删除成功');
                        this.fetchNews(); // 重新获取新闻公告
                        this.showDetailsModal = false; // 关闭弹窗
                    })
                    .catch(error => {
                        console.error(error);
                        alert('删除失败');
                    });
            },
            showUserDetails(user) {
                this.userInfo = user; // 设置 userInfo 数据
                this.showUserDetailsModal = true; // 显示详情对话框
            },
            deleteUser() {
                axios.delete(`/user/delete/${this.userInfo.id}`)
                    .then(response => {
                        alert('用户删除成功');
                        this.showUserDetailsModal = false;
                        this.userInfo = {};
                    })
                    .catch(error => {
                        console.error(error);
                        alert('删除失败');
                    });
            },
            fetchUserList() {
                axios.get('/admin/select')
                    .then(response => {
                        this.userList = response.data;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            // addProduct() {
            // //     const formData = new FormData();
            // //
            //
            // //     formData.append('name', this.newcategories.name);
            // //     formData.append('price', this.newcategories.price);
            // //     formData.append('kind', this.newcategories.kind);
            // //
            //
            // //     const file = this.$refs.upload.uploadFiles[0]?.raw;
            // //     if (file) {
            // //         formData.append('image', file);
            // //     } else {
            // //         this.$message.error('请上传商品图片');
            // //         return;
            // //     }
            // //
            //
            // //     for (let pair of formData.entries()) {
            // //         console.log(pair[0] + ": " + pair[1]);
            // //     }
            // //
            //
            //     axios.post('/admin/upload', formData)
            //         .then(response => {
            //             alert('商品添加成功');
            //             this.showAddProductModal = false;
            //             this.newcategories = { name: '', price: '', kind: '', image: '' };
            //             this.fetchCategories('list'); // 刷新商品列表
            //         })
            //         .catch(error => {
            //             console.error(error);
            //             alert('添加失败');
            //         });
            // },
            addProduct() {
                axios.post('/admin/upload', this.newcategories)
                    .then(response => {
                        alert('商品添加成功');
                        this.showAddProductModal = false;
                        this.newcategories = {name: '', price: '', kind: '', image: ''};
                        this.fetchCategories('list'); // 刷新商品列表
                    })
                    .catch(error => {
                        console.error(error);
                        alert('添加失败');
                    });
            },
            handleSuccess(response, file) {
                this.newcategories.image = URL.createObjectURL(file.raw);
            },
            handleError(err, file) {
                console.error('上传失败', err);
            },
            beforeUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传图片只支持 JPG/PNG 格式!');
                    return false;
                }
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                    return false;
                }
                return true;
            },
            handleFileUpload(event) {
                const file = event.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);

                    axios.post('/upload', formData, {
                        headers: {
                            // 'Content-Type': 'multipart/form-data'
                        }
                    })
                        .then(response => {
                            console.log('Upload successful:', response.data);
                            this.newcategories.image = response.data.url; // 假设后端返回上传图片的URL
                        })
                        .catch(error => {
                            console.error('Upload failed:', error);
                        });
                }
            },
            openCategoryModal(category) {
                this.selectedCategory = {...category};
                this.showCategoryModal = true;
            },
            updateCartItem(item) {


                axios.post('/admin/genggai', item)
                    .then(response => {
                        alert('购物车商品更新成功');
                        this.fetchCategories('list');
                        this.showCategoryModal = false;
                    })
                    .catch(error => {
                        console.error('更新失败', error);
                        alert('更新失败');
                    });

            },
            deleteCartItem(itemId) {
                axios.delete(`/admin/${itemId}`)
                    .then(response => {
                        alert('商品删除成功');
                        this.fetchCategories('list'); // 刷新商品列表
                        this.showCategoryModal = false;
                    })
                    .catch(error => {
                        console.error('删除失败', error);
                        alert('删除失败');
                    });
            },
        }
    });


</script>
</body>
</html>